package shajie.shajun.mmhf.View.Fragment;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import shajie.shajun.mmhf.Adapter.Spinner_Adapter;
import shajie.shajun.mmhf.Base.BaseFragment;
import shajie.shajun.mmhf.Bean2.OutGoods;
import shajie.shajun.mmhf.Bean2.PostPriceResult;
import shajie.shajun.mmhf.Bean2.Product;
import shajie.shajun.mmhf.Bean2.Result;
import shajie.shajun.mmhf.Public_Data;
import shajie.shajun.mmhf.R;
import shajie.shajun.mmhf.View.MainActivity;
import shajie.shajun.mmhf.ViewModel.Bmobdata;
import shajie.shajun.mmhf.databinding.FragmentAddoutgoodsBinding;

import static android.content.ContentValues.TAG;

/**
 * Created by admin on 2018/1/28.
 */

public class AddOutGoods_Frgment extends BaseFragment<FragmentAddoutgoodsBinding> implements View.OnClickListener {
    public FragmentAddoutgoodsBinding mBinding;
    private List<List<Product>> producttypes;
    private Spinner_Adapter spinner_adapter;
    private boolean flag=false;
    private boolean ismodify=false;
    private OutGoods mOutGoods=null;
    public static AddOutGoods_Frgment NewInten(OutGoods outGoods){
        AddOutGoods_Frgment addOutGoods_frgment=new AddOutGoods_Frgment();
        addOutGoods_frgment.setOutGoods(outGoods);
        return addOutGoods_frgment;
    }
    @Override
    public int setlayoutid() {
        return R.layout.fragment_addoutgoods;
    }

    @Override
    public void init(FragmentAddoutgoodsBinding binding) {
        this.mBinding=binding;
        Log.e(TAG, "NewInten: 2" );
        Public_Data.number++;
        mBinding.setOnclicklistener(this);
        mBinding.producttype.setAdapter(new Spinner_Adapter(getContext(),getContext().getResources().getStringArray(R.array.producttype)));
        if(mOutGoods.getDate()!=null&&!TextUtils.isEmpty(mOutGoods.getDate())){
            ismodify=true;
            mOutGoods.setDate(mOutGoods.getDate().replace('\n', '-'));
            Log.e(TAG, "NewInten: 1" );
            mBinding.sendoutgoods.setText("修改");
        }else {
            mOutGoods.setDate(setDate());
        }
        mBinding.setOutgoods(mOutGoods);
        getProductDetail();
        mBinding.producttype.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (producttypes==null)return;
                spinner_adapter.setStringArray(changetoarray(producttypes.get(position)));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        mBinding.spinnerProducts.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {
                if (!flag){
                    flag=true;
                    return;
                }
                new AlertDialog.Builder(getActivity()) // build AlertDialog
                        .setTitle("选择数量") // title
                        .setItems(R.array.number, new  DialogInterface.OnClickListener() { //content
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String s= TextUtils.isEmpty(mBinding.productsNumber.getText())?"":mBinding.productsNumber.getText().toString()+"/";

                                mBinding.productsNumber.setText(s+spinner_adapter.getStringPostion(position)+(which==0?"":"*"+(which+1)));

                            }
                        }) .show();


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
    private String[] changetoarray(List<Product> s){
    ArrayList<String> arrayList=new ArrayList<>();
    for (int i = 0; i < s.size(); i++) {
        arrayList.add(s.get(i).getProduct());
    }
    return (String[])arrayList.toArray(new String[arrayList.size()]);
}
    private void setOutGoods(OutGoods outGoods){
        try {
            this.mOutGoods=(OutGoods)outGoods.clone();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    private String setDate(){
        Calendar c2 = Calendar.getInstance();
        int year = c2.get(Calendar.YEAR);//年份
        int month = c2.get(Calendar.MONTH) + 1; //月份
        int date = c2.get(Calendar.DATE);//日期
       // Toast.makeText(getContext(), String.valueOf(year)+"-"+String.valueOf(month)+"-"+String.valueOf(date), Toast.LENGTH_SHORT).show();
        String syear=String.valueOf(year);
        String smonth=month<10?"0"+String.valueOf(month):String.valueOf(month);
        String sdate=date<10?"0"+String.valueOf(date):String.valueOf(date);
        return syear+"-"+smonth+"-"+sdate;
    }
    private boolean checkcontrol(){
        if (mBinding.postprice.getText().toString().indexOf("/")>0||mBinding.postprice.getText().toString().indexOf(" ")>0||Float.valueOf(mBinding.postprice.getText().toString()).floatValue()==0.0f){
            toast("邮费错误");
            return false;
        }

        if (Float.valueOf(mBinding.paidprice.getText().toString()).floatValue()==0.0f){
            return false;
        }else {
            if (checkEdittext(mBinding.paidprice) && checkEdittext(mBinding.productsNumber) && checkEdittext(mBinding.address) && checkEdittext(mBinding.weight)) {
                String reg="([\\\u4e00-\\\u9fa5c]{2,7}(\\*\\d)?/)*([\\\u4e00-\\\u9fa5c]{2,7}(\\*\\d)?)";
                boolean b=Pattern.matches(reg,mBinding.productsNumber.getText().toString());
                return b;
            }else
                return false;
        }
    }
    private boolean checkEdittext(EditText edittext){
       if(edittext.getInputType()==InputType.TYPE_CLASS_NUMBER){
           if (Integer.valueOf(edittext.getText().toString()).intValue()==0)
               return false;
           else
               return true;
       }else {
           if (TextUtils.isEmpty(edittext.getText().toString()))
               return false;
           else
               return true;

       }
    }
    private void getProductDetail(){
        Bmobdata.getproductdetail(getContext().getApplicationContext(),new Bmobdata.Singer<List<List<Product>>>() {
            @Override
            public void success(List<List<Product>> s) {
                if (getContext()==null||getContext().getApplicationContext()==null)
                    return;
                producttypes=s;
                spinner_adapter= new Spinner_Adapter(getContext(),changetoarray(s.get(0)));
                mBinding.spinnerProducts.setAdapter(spinner_adapter);
            }

            @Override
            public void faile(String s) {
                toast(s);
            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.computerpostprice:
                Map<String,String> maps=new HashMap<>();
//                maps.put("id","PostPrice");
                maps.put("Address",mBinding.address.getText().toString());
                maps.put("Weight",mBinding.weight.getText().toString());
                Bmobdata.computepostprice(getContext(), maps, new Bmobdata.Singer<PostPriceResult>() {
                    @Override
                    public void success(PostPriceResult s) {
                        mBinding.postprice.setText(s.getData());
                    }

                    @Override
                    public void faile(String s) {

                    }
                });
                break;
            case R.id.sendoutgoods:
                if (!checkcontrol()) {
                    toast("数据填写有误，请检查");
                    return;
                }

               // Date=2017-01-03&Product=cc霜*2/冰晶凝霜*3&PaidPrice=12.3&Weight=3&PostPrice=25&Address=江苏
                Map<String, String> map2s = new HashMap<>();
                if (!ismodify) {
                    map2s.put("id", "AddConsignment");
                    map2s.put("Date", mBinding.btnData.getText().toString());
                    map2s.put("Product", mBinding.productsNumber.getText().toString());
                    map2s.put("PaidPrice", mBinding.paidprice.getText().toString());
                    map2s.put("Weight", mBinding.weight.getText().toString());
                    map2s.put("PostPrice", mBinding.postprice.getText().toString());
                    map2s.put("Address", mBinding.address.getText().toString());
                    Bmobdata.addOutGoods(getContext(), map2s, new Bmobdata.Singer<Result>() {
                        @Override
                        public void success(Result s) {
                            if (s==null){
                                toast("添加失败null");
                                return;
                            }
                            if (s.getResult().contains("rue")) {
                                toast("添加成功");
                                ((MainActivity)getActivity()).refresh();
                                getFragmentManager().popBackStack();
                            }else
                                toast("添加失败");
                        }

                        @Override
                        public void faile(String s) {

                        }
                    });
                }else {
                    //interface.ashx?id=ModifyPostPrice&Key=11&Product=cc霜*2/冰晶凝霜*3&PaidPrice=12&Weight=3&PostPrice=25&Address=江苏&Clear=0&Date=2017-01-28
                    map2s.put("id", "ModifyConsignment");
                    map2s.put("Key", ""+mOutGoods.getID());
                    map2s.put("Date", mBinding.btnData.getText().toString());
                    map2s.put("Product",  mBinding.productsNumber.getText().toString());
                    map2s.put("PaidPrice", mBinding.paidprice.getText().toString());
                    map2s.put("Weight", mBinding.weight.getText().toString());
                    map2s.put("PostPrice", mBinding.postprice.getText().toString());
                    map2s.put("Address", mBinding.address.getText().toString());
                    map2s.put("Clear", mOutGoods.getClear().contains("rue")?"1":"0");
                    Bmobdata.addOutGoods(getContext(), map2s, new Bmobdata.Singer<Result>() {
                        @Override
                        public void success(Result s) {
                            if (s==null){
                                toast("修改失败null");
                                return;
                            }
                            if (s.getResult().contains("rue")) {
                                toast("修改成功");
                                ((MainActivity)getActivity()).refresh();
                                getFragmentManager().popBackStack();
                            }else
                                toast("修改失败");
                        }

                        @Override
                        public void faile(String s) {

                        }
                    });
                }
                break;
            case R.id.btn_data:
                Calendar calendar= Calendar.getInstance();
                DatePickerDialog dpd2 = new DatePickerDialog(getContext(), Datelistener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dpd2.show();
                break;
        }
    }
    private DatePickerDialog.OnDateSetListener Datelistener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {
                String month="";
                String day="";
                if (monthOfYear<9){
                    month="0"+(monthOfYear+1);
                }else {
                    month=""+(monthOfYear+1);
                }
                if (dayOfMonth<10){
                    day="0"+dayOfMonth;
                }else {
                    day=""+dayOfMonth;
                }
                mBinding.btnData.setText(myyear + "-" +month + "-" + day);
        }
    };

    @Override
    public void onDestroy() {
        Public_Data.number--;
        super.onDestroy();
    }
}
